package Demo1;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet({"/user/exit","/user/login"})
public class UserMethod extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        if("/user/exit".equals(path)){
            doExit(req,resp);
        }else if("/user/login".equals(path)){
            doLogin(req,resp);
        }

    }

    private void doExit(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException{
        HttpSession session = req.getSession(false);
        if(session!=null){
            // 关闭session
            session.invalidate();
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
        }
    }

    private void doLogin(HttpServletRequest req, HttpServletResponse resp) throws  IOException,ServletException{

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        connection = DBUtil.getConnection();
        String sql = "select username,password from t_user where username = ? and password = ?";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                // 成功就将User存进session对象
                User user = new User(username,password);
                HttpSession session = req.getSession();
                session.setAttribute("User",user);
                resp.sendRedirect(req.getContextPath()+"/dept/list");
            }
            else{
                // 失败就重定向到error界面.
                resp.sendRedirect(req.getContextPath()+"/error.jsp");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(connection,preparedStatement,resultSet);
        }
    }
}
